<template>
  <Top-Page class="login-index">
    <view class="login-bg"></view>

    <view class="login-content">
      <view class="head">
        <view class="logo-blue"></view>
        <view class="logo-text">畅了</view>
      </view>

      <view class="from-wrap">
        <form>
          <Field
            clearable
            :maxlength="11"
            :leftIcon="'../../static/image/login/account.png'"
            autocomplete="off"
            v-model.trim="loginForm.account"
            placeholder="请输入账号"
          />

          <Field
            v-if="!forget"
            type="password"
            clearable
            :maxlength="50"
            :leftIcon="'../../static/image/login/password.png'"
            autocomplete="off"
            v-model.trim="loginForm.password"
            placeholder="请输入密码"
          />

          <Field
            v-else
            autosize
            type="text"
            :maxlength="11"
            autocomplete="off"
            v-model.trim="loginForm.code"
            placeholder="请输入验证码"
          >
            <template #button>
              <view :class="['code-btn', { 'code-btn__disabled': count_down }]" @click.stop="sendCode">
                {{ codeText }}
                <span v-if="count_down > 0">{{ count_down }}s</span>
              </view>
            </template>
          </Field>
        </form>

        <view class="btn login-btn" @click.stop="login()">登录</view>

        <view
          :class="['btn', 'register-btn', { 'novice-guide-operate': !noviceGuide.includes(0) }]"
          @click.stop="register()"
        >
          注册
        </view>

        <view class="forget">
          <view>
            <switch
              class="switch"
              :checked="loginForm.rememberMe"
              :class="loginForm.rememberMe ? 'checked' : ''"
              @change="switchChange"
              style="transform: scale(0.7)"
            />
            记住我
          </view>
          <view @tap="(forget = !forget), (loginForm.code = '')">
            {{ forget ? "密码登陆" : "快速登陆" }}
          </view>
        </view>
      </view>

      <view class="novice-guide-location">
        <view class="novice-guide-title novice-guide-title-wrap" v-if="!noviceGuide.includes(0)">
          <view class="novice-guide-title">欢迎加入</view>
          <view class="novice-guide-title">“畅了”聊天社区</view>
        </view>
        <view class="novice-guide-text" v-if="!noviceGuide.includes(0)">
          点击“注册”按钮，填写您的基本信息，完成验证后即可成为我们的会员
        </view>
      </view>

      <view class="agreement">
        <image
          class="checked"
          src="../../static/image/login/checked.png"
          v-if="agreementStatus"
          @click.stop="agreementStatus = false"
        ></image>
        <image
          v-else
          class="checked"
          src="../../static/image/login/un-checked.png"
          @click.stop="agreementStatus = true"
        ></image>
        <view class="text" @click.stop="agreementStatus = !agreementStatus">阅读并同意</view>
        <view class="agreement-item" @click.stop="toAgreement(1)">《畅了隐私保护指引》</view>
        <view @click.stop="toAgreement(4)">《服务协议》</view>
      </view>
    </view>
  </Top-Page>

  <view class="novice-guide-box" v-if="!noviceGuide.includes(0)"></view>
</template>

<script>
import Field from "@/components/Field/Field.vue";
import { useloginStore } from "@/store/login";
import { initSDK } from "@/utils/trtc.js";
import pinia from "@/store/index";
import packageData from "../../package.json";
import { useAddAutoFirend } from "@/hooks/useAddAutoFirend.js";
import { userIdFriendKey } from "@/enums/CacheEnums.js";
const loginStore = useloginStore(pinia);
export default {
  data() {
    return {
      agreementStatus: false,
      noviceGuide: uni.getStorageSync("noviceGuide") || [],
      loginForm: {
        account: "",
        password: "",
        code: "",
        client_id: "",
        rememberMe: false,
      },
      count_down: 0,
      codeText: "发送验证码",
      time: null,
      forget: false,
      packData: packageData,
      globalConfig: loginStore.globalConfig,
    };
  },
  components: { Field },
  watch: {
    // forget(val) {
    // 	if (val) {
    // 		this.loginForm.password = "123456"
    // 	}
    // },
  },
  onUnload() {
    this.time && clearInterval(this.time);
  },
  mounted() {
    // #ifdef H5
    if (process.env.NODE_ENV === "development") {
      this.loginForm.account = "13800000009";
      this.loginForm.password = "123456";
      this.agreementStatus = true;
    }
    // #endif
    // #ifdef APP
    //清空所有推送消息
    plus.push.clear();
    // #endif

    if (this.globalConfig && this.globalConfig.demon_mode) {
      const random = Math.floor(Math.random() * 19 + 2);
      this.loginForm.account = 13800000000 + random;
      this.loginForm.password = "123456";
    }
    let LoginAccount = uni.getStorageSync("LoginAccount");
    if (LoginAccount) {
      this.loginForm = LoginAccount;
    }

    this.noviceGuide.push(
      ...[0, 1, 2, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]
    );
    uni.setStorageSync("noviceGuide", this.noviceGuide);

    if (process.env.NODE_ENV === "development") {
      let ng = [];
      for (let i = 0; i <= 30; i++) {
        ng.push(i);
      }
      uni.setStorageSync("noviceGuide", ng);
    }
  },
  methods: {
    toAgreement(id) {
      uni.navigateTo({
        url: `/pages/agreement/index?id=${id}`,
      });
    },
    switchChange(e) {
      this.loginForm.rememberMe = e.detail.value;
    },
    sendCode() {
      if (this.count_down > 0) return;
      if (!this.loginForm.account) {
        uni.showToast({
          title: "请输入账号！",
          icon: "none",
        });
        return false;
      }
      let data = {
        account: this.loginForm.account,
        type: 1,
      };

      this.count_down = 60;
      this.codeText = "重新发送";
      this.time = setInterval(() => {
        this.count_down--;
        if (this.count_down <= 0) {
          clearInterval(this.time);
        }
      }, 1000);

      this.$api.LoginApi.sendCode(data).then((res) => {
        uni.showToast({
          title: res.msg,
          icon: "none",
        });
      });
    },
    register() {
      if (!this.noviceGuide.includes(0)) {
        this.noviceGuide.push(0);
        uni.setStorageSync("noviceGuide", this.noviceGuide);
      }

      uni.navigateTo({
        url: "/pages/login/register",
      });
    },
    addOrUpdateUserData(existingData, newUserData, userId) {
      // 遍历现有的对象，查找是否有相同的 user_id
      for (const key in existingData) {
        if (existingData[key].user_id === userId) {
          delete existingData[key];
        }
      }

      return Object.assign(existingData, newUserData);
    },
    login() {
      if (this.loginForm.rememberMe) {
        uni.setStorageSync("LoginAccount", this.loginForm);
      } else {
        uni.removeStorageSync("LoginAccount");
      }
      if (this.loginForm.account == "") {
        uni.showToast({
          title: "请输入账号！",
          icon: "none",
        });
        return false;
      }
      if (this.loginForm.password == "") {
        uni.showToast({
          title: "请输入密码！",
          icon: "none",
        });
        return false;
      }
      if (!this.agreementStatus) {
        uni.showToast({
          title: "请先勾选相关协议！",
          icon: "none",
        });
        return false;
      }
      let client_id = uni.getStorageSync("client_id");
      if (client_id) {
        this.loginForm.client_id = client_id;
      }
      this.$api.LoginApi.login(this.loginForm).then((res) => {
        if (res.code == 0) {
          const token = res.data.token;
          uni.setStorageSync("authToken", res.data.authToken);
          uni.setStorageSync("Token", token);

          //多账户
          let newUserData = {};
          newUserData[token] = res.data.userInfo;

          const existingData = JSON.parse(uni.getStorageSync("multiAccounts") || "{}");
          const newData = Object.assign(this.addOrUpdateUserData(existingData, newUserData, res.data.userInfo.user_id));

          uni.setStorageSync("multiAccounts", JSON.stringify(newData));

          let userInfo = res.data.userInfo;

          //初始化放大基数
          this.initMagnify(userInfo.pagesize || 1);

          // 登录成功后绑定wss
          this.socketIo.send({
            type: "bindUid",
            user_id: userInfo.user_id,
            token: res.data.authToken,
          });
          loginStore.login(userInfo);

          // 初始化腾讯云音视频SDK
          initSDK(userInfo.user_id);

          //获取emoji表情包
          this.getEmoji();

          // 是否添加自动好友
          useAddAutoFirend(userIdFriendKey);

          if (!!userInfo.identity) {
            uni.reLaunch({
              url: "/pages/index/index",
            });
          } else {
            uni.showToast({
              title: "请先完成实名认证",
              icon: "none",
            });
            uni.reLaunch({
              url: "/pages/mine/profile/real-name",
            });
          }
        }
      });
    },
    getEmoji() {
      this.$api.msgApi.emoji().then((res) => {
        if (res.code == 0) {
          uni.setStorageSync("emojiList", res.data);
        }
      });
    },
    initMagnify(num) {
      // // #ifdef H5
      // document.documentElement.style.setProperty('--amplified_base', num);
      // // #endif

      uni.setStorageSync("amplifiedBase", num);
    },
  },
};
</script>

<style scoped lang="scss">
@import "./index.scss";
@import "./login-bg.scss";
.agreement {
  image {
    display: block;
    width: 30rpx;
    height: 30rpx;
  }
}
.login-logo {
  width: 180rpx;
  height: 180rpx;
  font-size: 80rpx;
  text-align: center;
  line-height: 120rpx;
  border-radius: 18rpx;
}

.forbid {
  opacity: 0.6;
}
.footer-version {
  width: 100%;
  text-align: center;
  position: fixed;
  bottom: 40rpx;
}
.remark-title {
  font-weight: 600;
}
.im-reg-btn {
  padding: 30rpx;
}
.im-login-btn {
  padding: 0 30rpx;
}
.forget {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  padding: 30rpx;
}

.novice-guide-title-wrap {
  position: absolute;
  top: -300rpx;
  width: 100%;
  font-weight: 400;
  font-size: 60rpx;
  color: #ffffff;
  line-height: 90rpx;
  text-align: center;
}

.novice-guide-text {
  margin-top: 30rpx;
}
</style>
